$(function(){
    goLogin();
    var productId = $.getUrlParam('productid');
    var designType = $.getUrlParam('designType');
    var cartId = $.getUrlParam('cartid');

    var keys, flag = false , _dsgid = [], oldDsgIds=[], _msgId = 1,
        chooseLength, designerDom, _num, arr
    var ii=0, iii=0, iv=0, v=0, vi=0;

    $('.packingFee').val(0);

    if(designType == 'DESIGN'){
        $('.ifTab').removeClass('tab');
        $('.pack-design').addClass('tab');
    }else if(designType == 'ORIGINAL'){
        $('.auto').text('原厂购买');
        $('.standard>h4').text('商品规格');
        $('.buyNum').text('购买数量');
        $('.online-design').addClass('tab');
        // $('.user-tel').addClass('tab');
    }

    goBack()
    getInitData(productId,cartId);
    getUserInfo();
    submitFn(designType);
    operationFn();

    // FUN
    function getOldDataA(id){
        console.log('plan:A')
        post({
            url:'/customizeCart/'+id+'/detail',
            success:function(data){
                console.log(data)
                $('.now-design').val('保存').css({
                    'width':'66.66%',
                    'background':'#ff7900',
                    'color':'#fff'
                })
                $('.normal-buy').addClass('tab');
                var arrayA = data["manufacturerSpecGroup"]["attrIds"].split(',');
                console.log(data);
                setTimeout(function() {
                    for(var i=0; i<arrayA.length; i++){
                        console.log(i)
                        $('.click_A_'+arrayA[i]).click();
                    }
                    // $('.click_A_'+arrayA[0]).click();
                    // $('.click_A_'+arrayA[1]).click();
                    if(designType == 'DESIGN'){
                        $('._packItemList_'+data["csId"]).click();
                    }
                    if(data["cartDesignerList"].length != 0){
                        localStorage.setItem('cartDesignerIds',data['cardDesignerIds'])
                        $('.editType').text('编辑')
                    }
                    setTimeout(function() {
                        $('.productionTotal').text(returnFloat(parseFloat($('._minPrice').text())*parseFloat(data["num"])));
                        $('.sumPrice').text(returnFloat(parseFloat($('._minPrice').text())*parseFloat(data["num"])));
                        if(designType == 'DESIGN'){
                            designerDom = data["designer"]["id"]
                            oldDsgIds = data.dsgAttrIds.split(',');
                        }
                        $('._contact').val(data["contact"]);
                        $('._contactTel').val(data["contactTel"]);
                        $('._designNum').val(data["num"]);
                        _num = data["num"]
                    }, 100);
                }, 100);
            }
        })
    }

    function getOldDataB(data){
        console.log('plan:B')
        // localStorage.setItem('_oldData','');
        if(cartId){
            $('.now-design').val('保存').css({
                    'width':'66.66%',
                    'background':'#ff7900',
                    'color':'#fff'
                })
            $('.normal-buy').addClass('tab');
        };
        var arrayA = data["manufacturerSpecGroup"]["attrIds"].split(',');
        console.log(arrayA);
        setTimeout(function() {
            for(var i=0; i<arrayA.length; i++){
                $('.click_A_'+arrayA[i]).click();
            }
            // $('.click_A_'+arrayA[0]).click();
            // $('.click_A_'+arrayA[1]).click();
            if(designType == 'DESIGN'){
                $('._packItemList_'+data["csId"]).click();
            };
            $('.editType').text('编辑');
            setTimeout(function() {
                $('.productionTotal').text(returnFloat(parseFloat($('._minPrice').text())*parseFloat(data["num"])));
                $('.sumPrice').text(returnFloat(parseFloat($('._minPrice').text())*parseFloat(data["num"])));
                if(designType == 'DESIGN'){
                    designerDom = data["designer"]["id"]
                    oldDsgIds = data.dsgAttrIds.split(',');
                }
                $('._contact').val(data["contact"]);
                $('._contactTel').val(data["contactTel"]);
                $('._designNum').val(data["num"]);
                _num = data["num"]
            }, 100);
        }, 10);
    }

    function getInitData(productId,cartId){
        post({
            url:'/customizeProduct/'+productId+'/detail',
            success:function(data){
                handleInitData(data)
                if(localStorage.getItem('_oldData')){
                    getOldDataB(JSON.parse(localStorage.getItem('_oldData')));
                    localStorage.setItem('_oldData','')
                }else if(cartId){
                    getOldDataA(cartId);
                }
            }
        })
    };

    function handleInitData(data){
        console.log(data)
        //属性集
        keys = data["matchList"]
        var mainData = {
            productName:data["product"]["name"],
            manufacturersName:data["manufacturers"][0]["name"],
            main_img:data["product"]["imageUrl"],
            minPrice:returnFloat(data["product"]["minPrice"])+'/箱起'
        };
        localStorage.setItem('mainData',JSON.stringify(mainData))   //初始介绍数据
        // part 1
        $('._productName').text(data["product"]["name"]);
        $('._manufacturersName').text(data["manufacturers"][0]["name"]);
        $('.main-img').attr('src',SERVER_CONTEXT_PATH+'/load/picture/'+data["product"]["imageUrl"]);
        $('._minPrice').text(returnFloat(data["product"]["minPrice"])+'/箱起');
        // part 2
        $('.manufacturerId').val(data["manufacturers"][0]["id"]);
        var specificationItem = data["manufacturers"][0]["specification"];
        $('.itemLength').val(specificationItem.length);
        chooseLength = new Array(parseFloat($('.itemLength').val()));
        for(var i=0; i<specificationItem.length; i++){
            $('.standardItem').append(
                
                '<div data-key="'+i+'" class="taste taste_'+i+'">'
                    +'<span>【'+specificationItem[i]["name"]+'】</span>'
                    +'<ul class="clear itemList_'+specificationItem[i]["id"]+'"></ul>'
                +'</div>'
                
            );
            for(var j=0; j<specificationItem[i]["attributes"].length; j++){
                $('.itemList_'+specificationItem[i]["id"]).append(
                    // '<input type="button" class="itemListData sku" attr_id="'+specificationItem[i]["attributes"][j]["id"]+'" value="'+specificationItem[i]["attributes"][j]["name"]+'"/>'
                    '<input data-id="'+specificationItem[i]["attributes"][j]["id"]+'" data-key="'+[i]+'" type="button" class="itemListData sku click_A_'+specificationItem[i]["attributes"][j]["id"]+'" attr_id="'+specificationItem[i]["attributes"][j]["id"]+'" value="'+specificationItem[i]["attributes"][j]["name"]+'"/>'
                )
            }
        };
        // part 3
        for(var i=0; i<data["customizeSpecifications"].length; i++){
            $('._packItem').append(
                '<li class="_packItemList_'+data["customizeSpecifications"][i]["id"]+'" data-id="'+data["customizeSpecifications"][i]["id"]+'">'
                    +'<img src="'+SERVER_CONTEXT_PATH+'/load/picture/'+data["customizeSpecifications"][i]["imageUrl"]+'" alt="">'
                +'</li>'
            )
        }
        arr = new Array($('.taste').length);
    };

    function getSecondData(chooseLength){
        var data = {
            attrIds: chooseLength.toString(),
            manufacturerId: $('.manufacturerId').val(),
            productId: productId
        };
        post({
            url:'/customizeProduct/manufacturerDetail',
            data:data,
            success:function(data){
                // console.log(data)
                _msgId = data.id;
                $('.main-img').attr('src',SERVER_CONTEXT_PATH+'/load/picture/'+data.imageUrl);
                if(_num){
                    $('._designNum').val(_num)
                }else{
                    $('._designNum').val(data.moq);
                };
                $('.moqNum').val(data.moq);
                $('.moqNum>i').text(data.moq);
                $('._minPrice').text(returnFloat(data.totalPrice)+'/箱');
                $('.productionTotal').text(returnFloat(data.totalPrice*data.moq));
                $('.sumPrice').text(returnFloat(parseFloat($('.productionPrice').text())+parseFloat($('.productionTotal').text())+parseFloat($('._designFee').text())))
            }
        });
    };

    function getThirdData(id){
        var data = {
            csId: id,
            productId: productId
        };
        post({
            url:'/customizeProduct/designerList',
            data:data,
            success:function(data){
                $('.ifTab_A').removeClass('tab');
                window.localStorage.setItem('thirdData',JSON.stringify(data));
                handleThirdData(data);
                setTimeout(function() {
                    $('._designer_'+designerDom).click();
                    $('._designer>li').eq(0).click();
                    for(var i = 0; i<oldDsgIds.length; i++){
                        $('.detailList_'+oldDsgIds[i]).click();
                    };
                    oldDsgIds = [];
                }, 100);
            }
        })
    }

    function handleThirdData(data){
        // console.log(data);
        $('._designer').empty();
        for(var i=0; i<data["specificationDto"].length; i++){
            $('._designer').append(
                '<li class="_designer_'+data["specificationDto"][i]["id"]+'" data-id="'+data["specificationDto"][i]["id"]+'" data-key="'+i+'">'
                    +'<img src="'+SERVER_CONTEXT_PATH+'/load/picture/'+data["specificationDto"][i]["designerPictures"][0]+'" alt="">'
                +'</li>'
            )
        };
    }

    function getUserInfo(){
        post({
            url: '/customizeOrder/findMember',
            success:function(data){
                // console.log(data)
                $('._contact').val(data.contact);
                $('._contactTel').val(data.contactTel);
            }
        })
    }

    function submitFn(designType){
        // 加入购物车
        $('.now-design').click(function(){
            judge();
            if(designType == 'DESIGN'){
                if(!_msgId){
                    $('.gat_alert>p').text('请填写商品定制。');
                    $('.gat_background').removeClass('tab');
                    return;
                }
                var data = {
                    isBuyNow:false,
                    cartId: parseFloat(cartId),
                    designType: designType,
                    msgId: parseFloat(_msgId.toString()),
                    csId: parseFloat($('.csId').val()),
                    num: parseFloat($('._designNum').val()),
                    dsgIds: _dsgid.toString(),
                    // cartDesignerIds: $('.cartDesignerIds').val(),
                    cartDesignerIds: localStorage.getItem('cartDesignerIds'),
                    contact: $('._contact').val(),
                    contactTel:$('._contactTel').val()
                }
                if(ii != $('.standardItem>div').length){
                    $('.gat_alert>p').text('请填写商品定制信息。')
                    $('.gat_background').removeClass('tab');
                }else if(iii != 1){
                    $('.gat_alert>p').text('请选择包装设计。')
                    $('.gat_background').removeClass('tab');
                }else if(iv != 1){
                    $('.gat_alert>p').text('请选择设计商。')
                    $('.gat_background').removeClass('tab');
                }else if(v <= 0){
                    $('.gat_alert>p').text('请填写设计内容。')
                    $('.gat_background').removeClass('tab');
                }else if(vi != 1){
                    $('.gat_alert>p').text('请填写联系信息。')
                    $('.gat_background').removeClass('tab');
                }else {
                    submitPost('a',data)
                }
            }else if(designType == 'ORIGINAL'){
                var data = {
                    isBuyNow:false,
                    cartId: parseFloat(cartId),
                    designType: designType,
                    msgId: parseFloat(_msgId.toString()),
                    num: parseFloat($('._designNum').val()),
                    contact: $('._contact').val(),
                    contactTel:$('._contactTel').val()
                }
                if(ii != $('.standardItem>div').length){
                    $('.gat_alert>p').text('请填写商品定制信息。')
                    $('.gat_background').removeClass('tab');
                }else {
                    submitPost('a',data)
                }
            }

        })
        // 立即购买
        $('.normal-buy').click(function(){
            judge();
            if(designType == 'DESIGN'){
                var data = {
                    isBuyNow:true,
                    cartId: parseFloat(cartId),
                    designType: designType,
                    msgId: parseFloat(_msgId.toString()),
                    csId: parseFloat($('.csId').val()),
                    num: parseFloat($('._designNum').val()),
                    dsgIds: _dsgid.toString(),
                    // cartDesignerIds: $('.cartDesignerIds').val(),
                    cartDesignerIds: localStorage.getItem('cartDesignerIds'),
                    contact: $('._contact').val(),
                    contactTel:$('._contactTel').val()
                }
                if(ii != $('.standardItem>div').length){
                    $('.gat_alert>p').text('请填写商品定制信息。')
                    $('.gat_background').removeClass('tab');
                }else if(iii != 1){
                    $('.gat_alert>p').text('请选择包装设计。')
                    $('.gat_background').removeClass('tab');
                }else if(iv != 1){
                    $('.gat_alert>p').text('请选择设计商。')
                    $('.gat_background').removeClass('tab');
                }else if(v <= 0){
                    $('.gat_alert>p').text('请填写设计内容。')
                    $('.gat_background').removeClass('tab');
                }else if(vi != 1){
                    $('.gat_alert>p').text('请填写联系信息。')
                    $('.gat_background').removeClass('tab');
                }else {
                    submitPost('b',data)
                }
            }else if(designType == 'ORIGINAL'){
                var data = {
                    isBuyNow:true,
                    cartId: parseFloat(cartId),
                    designType: designType,
                    msgId: parseFloat(_msgId.toString()),
                    num: parseFloat($('._designNum').val()),
                    contact: $('._contact').val(),
                    contactTel:$('._contactTel').val()
                }
                if(ii != $('.standardItem>div').length){
                    $('.gat_alert>p').text('请填写商品定制信息。')
                    $('.gat_background').removeClass('tab');
                }else {
                    submitPost('b',data)
                }
            }
            
        })

    }

    function judge(){
        ii=0, iii=0, iv=0, v=0, vi=0;
        for(var i = 0; i<$('.itemListData').length; i++){
            if($('.itemListData').eq(i).hasClass('active')){
                ii+=1
            };
        };
        for(var i = 0; i<$('._packItem>li').length; i++){
            if($('._packItem>li').eq(i).hasClass('active')){
                iii+=1
            }
        }
        for(var i = 0; i<$('._designer>li').length; i++){
            if($('._designer>li').eq(i).hasClass('active')){
                iv+=1
            }
        }
        for(var i = 0; i<$('.design-detail>li').length; i++){
            if($('.design-detail>li').eq(i).hasClass('_selected')){
                v+=1
            }
        }
        if($('._contact').val()!='' && $('._contactTel').val()!=''){
            if($('._contact').val()!=null && $('._contactTel').val()!=null){
                vi=1
            }
        }
        console.log(ii,iii,iv,v,vi)
    }

    function submitPost(ab,data){
        if(ab == 'a'){
            post({
                url:'/customizeCart/saveCart',
                data:data,
                success: function(data){
                    localStorage.setItem('_oldData','');
                    localStorage.setItem('cartDesignerIds','');
                    console.log(data)
                    if(cartId){
                        go('/customize/cart/index.html')
                    }else{
                        $('.intoCart').removeClass('tab');
                        setTimeout(function() {
                            window.location.reload();
                        }, 1000);
                    }
                }
            })
        }else if(ab == 'b'){
            post({
                url:'/customizeCart/saveCart',
                data:data,
                success: function(data){
                    localStorage.setItem('_oldData','');
                    localStorage.setItem('cartDesignerIds','');
                    console.log(data)
                    var _data = data;
                    post({
                        url:"/customizeOrder/saveOrderCode",
                        data:{cartIds:_data},
                        success:function(data){
                            console.log(data);
                            localStorage.setItem("customize_order_return",window.location.href);
                            localStorage.setItem("customize_orderCode",data);
                            localStorage.setItem("customize_cartIds",_data);
                            go("/mobileorder/order_confirm.html");
                        }
                    });
                }
            })
        }
    }

    function goBack(){
        $('.go-back').click(function(){
            localStorage.setItem('_oldData','');
            localStorage.setItem('cartDesignerIds','');
            go(localStorage.getItem('selectdesign_goBackUrl'))
        })
    }

    function operationFn(){
        // operat 1
        $('.standardItem').delegate('.itemListData','click',function(){
            if($(this).hasClass('_dash')){
                return;
            }
            $('.ifTab_B').addClass('tab');
            $('.ifTab_A').addClass('tab');
            $('._packItem>li').removeClass('active');
            $('._designer>li').removeClass('active');
            $('.design-detail>li').removeClass('_selected');
            if($(this).hasClass('active')){
                console.log(1)
                chooseLength.splice($(this).data('key'),1,null);
            }else{
                console.log(2)
                chooseLength.splice($(this).data('key'),1,$(this).data('id'));
            }
            console.log(chooseLength.filter(function(n){return n}))
            var chooseLengthNum =(chooseLength.filter(function(n){return n})).length;
            // chooseLength.splice($(this).data('key'),1,$(this).data('id'));
            // chooseLength = chooseLength.filter(function(n){return n}).length;
            console.log(chooseLengthNum)
            console.log($('.taste').length)
            if(chooseLengthNum == $('.taste').length){
                getSecondData(chooseLength);
                $('.ifTab_C').removeClass('tab');
                $('.pack-design').removeClass('tab');
            }else{
                var mainData = JSON.parse(localStorage.getItem('mainData'));
                console.log(mainData)
                $('.pack-design').addClass('tab');
                $('._productName').text(mainData["productName"]);
                $('._manufacturersName').text(mainData['manufacturersName']);
                $('.main-img').attr('src',SERVER_CONTEXT_PATH+'/load/picture/'+mainData['main_img']);
                $('._minPrice').text(mainData['minPrice']);
            }
        });

        // operat 2
        $('.numAdd').click(function(){
            $('._designNum').val(parseFloat($('._designNum').val())+parseFloat(1))
            $('.productionTotal').text(returnFloat(parseFloat($('.productionTotal').text())+parseFloat($('._minPrice').text())))
            $('.productionPrice').text(returnFloat(parseFloat($('.packingFee').val())*parseFloat($('._designNum').val())))
        });
        $('.numReduce').click(function(){
            if(parseFloat($('._designNum').val())>parseFloat($('.moqNum').val())){
                $('._designNum').val(parseFloat($('._designNum').val())-parseFloat(1))
                $('.productionTotal').text(returnFloat(parseFloat($('.productionTotal').text())-parseFloat($('._minPrice').text())))
                $('.productionPrice').text(returnFloat(parseFloat($('.packingFee').val())*parseFloat($('._designNum').val())))
            }else{
                $('._designNum').val($('.moqNum').val())
            }
        });

        // operat 3
        $('._packItem').delegate('li','click',function(){
            $('._designer>li').removeClass('active');
            $('.design-detail>li').removeClass('_selected');
            $('._designFee').text(0);
            $('._packingFee').text(0);
            $('.packingFee').val(0);
            console.log(111)
            _dsgid = [];
            $('._designer>li').removeClass('active');
            $('.design-detail').removeClass('_selected');
            $(this).addClass('active').siblings().removeClass('active');
            $('.csId').val($(this).data('id'));
            getThirdData($(this).data('id'));
        });

        // operat 4
        $('.design-detail').delegate('li','click',function(){
            // console.log($(this))
            $(this).toggleClass('_selected');
            $('.ifTab_edit').removeClass('tab');
            var data = {
                attrId: $(this).data('id'),
                csId: $('.csId').val(),
                designerId: $('.designerId').val(),
                num: 1,
                productId: productId
            }
            // console.log(data);
            var _this = $(this)
            post({
                url:'/customizeProduct/designerDetail',
                data:data,
                success:function(data){
                    $('.productionPrice').text(returnFloat(data.packingFee*$('.moqNum').val()));
                    if(_this.hasClass('_selected')){
                        $('._designFee').text(returnFloat(parseFloat($('._designFee').text())+parseFloat(data.price)));
                        // console.log($('.packingFee').val())
                        $('.packingFee').val(returnFloat(parseFloat($('.packingFee').val())+parseFloat(data.packingFee)))
                        $('._packingFee').text($('.packingFee').val());
                        $('.productionPrice').text(returnFloat(parseFloat($('.packingFee').val())*parseFloat($('._designNum').val())))
                        _dsgid.push(data.id)
                    }else{
                        $('._designFee').text(returnFloat(parseFloat($('._designFee').text())-parseFloat(data.price)));
                        $('.packingFee').val(returnFloat(parseFloat($('.packingFee').val())-parseFloat(data.packingFee)));
                        $('._packingFee').text($('.packingFee').val());
                        $('.productionPrice').text(returnFloat(parseFloat($('.packingFee').val())*parseFloat($('._designNum').val())))
                        removeAry(_dsgid,data.id)
                    };
                    $('.sumPrice').text(returnFloat(parseFloat($('.productionPrice').text())+parseFloat($('.productionTotal').text())+parseFloat($('._designFee').text())))
                }
            })
        })

        // operat 5
        $('._contactTel').blur(function(){
            var ExgStr = /^1[34578]\d{9}$/;
            if(!ExgStr.test($('._contactTel').val())){
                $('._contactTel').val('');
            }
        });

        // operat 6
        $('body').click(function(){
            $('.sumPrice').text(returnFloat(parseFloat($('.productionPrice').text())+parseFloat($('.productionTotal').text())+parseFloat($('._designFee').text())))
        });

        // operat 7
        $('._designer').delegate('li','click',function(){
            $('.design-detail>li').removeClass('_selected');
            $('._designFee').text(0);
            $('._packingFee').text(0);
            $('.packingFee').val(0);
            _dsgid = [];
            $('.ifTab_B').removeClass('tab');
            $(this).addClass('active').siblings().removeClass('active');
            var key = $(this).data('key');
            var data = JSON.parse(window.localStorage.getItem('thirdData'));
            designerDom = $(this).data('id');
            $('.designerId').val(data["specificationDto"][key]["id"])
            var containList = data["specificationDto"][key]["attributes"];
            $('.designName').text(data["specificationDto"][key]["name"]);
            $('.alert_contain').html(data["specificationDto"][key]["remark"]);
            $('.design-detail').empty();
            for(var i=0; i<containList.length; i++){
                $('.design-detail').append(
                    '<li data-id="'+containList[i]["id"]+'" class="_unselected detailList_'+containList[i]["id"]+'">'
                        +'<label>'+containList[i]["name"]+'</label>'
                    +'</li>'
                )
            }
        });
        $('.designer').click(function(){
            jumpHTML();
            setTimeout(function() {
                go('/customize/designProduct/designer.html?designerId='+$('.designerId').val())
            }, 200);
            // $('.alert_bg').removeClass('tab');
        })

        // operat 8
        $('.ifTab_edit').click(function(){
            judge();
            if(v <= 0){
                $('.gat_alert>p').text('请填写设计内容。')
                $('.gat_background').removeClass('tab');
            }else{
                jumpHTML();
                setTimeout(function() {
                    go('./designcontain.html');
                }, 200);
            };
            
            // if(cartId){
            //     go('./designcontain.html?cartId='+cartId);
            // }else{
               
            // }
        });

        function jumpHTML(){
            var _attrIds = [], _dsgAttrIds = [];
            for(var i=0; i<$('.itemListData').length; i++){
                if($('.itemListData').eq(i).hasClass('active')){
                    _attrIds.push($('.itemListData').eq(i).data('id'))
                }
            };
            $('.design-detail>li')
            for(var i=0; i<$('.design-detail>li').length; i++){
                if($('.design-detail>li').eq(i).hasClass('_selected')){
                    _dsgAttrIds.push($('.design-detail>li').eq(i).data('id'))
                }
            }
            var _data={
                manufacturerSpecGroup:{
                    attrIds: _attrIds.toString()
                },
                csId: $('.csId').val(),
                designer:{
                    id: designerDom
                },
                dsgAttrIds: _dsgAttrIds.toString(),
                num: $('._designNum').val(),
                contact: $('._contact').val(),
                contactTel: $('._contactTel').val(),
            }
            localStorage.setItem('_oldData',JSON.stringify(_data));
            localStorage.setItem('dsgIds',_dsgid);
        }

        // operat 9
        $('.gat_background').click(function(){
            $('.gat_background').addClass('tab');
            $('.gat_alert>p').text('')
        })
    };
    // 数组处理
    function removeAry(data,delet){
        for(var i=0;i<data.length;i++){
            if(data[i]==delet){
                return data.splice(i,1)
            }
        }
    };

    localStorage.removeItem("invoice_id");//清除发票信息

});